<template>
  <div class="login-container">
    <div class="login-box">
      <h2>用户登录</h2>
      <!-- 手机号登录表单 -->
      <div v-if="loginType === 'phone'">
        <div class="form-group">
          <label>手机号</label>
          <input 
            type="text" 
            v-model="loginForm.phone" 
            placeholder="请输入手机号"
          >
        </div>
        <div class="form-group verification-code">
          <input 
            type="text" 
            v-model="loginForm.smsCode" 
            placeholder="请输入验证码"
          >
          <button 
            class="send-code-btn" 
            :disabled="countdown > 0"
            @click="handleSendSmsCode"
          >
            {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
          </button>
        </div>
      </div>

      <!-- 账号密码登录表单 -->
      <div v-else>
        <div class="form-group">
          <label>用户名</label>
          <input 
            type="text" 
            v-model="loginForm.username" 
            placeholder="请输入用户名"
          >
        </div>
        <div class="form-group">
          <label>密码</label>
          <input 
            type="password" 
            v-model="loginForm.password" 
            placeholder="请输入密码"
          >
        </div>
        <div class="form-group verification-code">
          <input 
            type="text" 
            v-model="loginForm.verificationCode" 
            placeholder="请输入验证码"
          >
          <div class="captcha-image" @click="refreshCaptcha">
            <canvas ref="captchaCanvas" width="120" height="40"></canvas>
          </div>
        </div>
      </div>

      <!-- 只在账号密码登录时显示"记住我"选项 -->
      <div class="remember-me" v-if="loginType === 'password'">
        <input 
          type="checkbox" 
          v-model="loginForm.remember"
        > 记住我
      </div>
      <button class="login-btn" @click="handleLogin">登录</button>
      
      <!-- 只在账号密码登录时显示忘记密码链接 -->
      <div class="other-actions" v-if="loginType === 'password'">
        <router-link to="/forgot-password">忘记密码？</router-link>
      </div>
      
      <div class="login-type-switch" @click="toggleLoginType">
        {{ loginType === 'phone' ? '账号密码登录' : '手机验证码登录' }}
      </div>
      
      <div class="third-party-login">
        <p>其他登录方式</p>
        <div class="login-methods">
          <span class="method-item">微信</span>
          <span class="method-item">QQ</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'  // 添加 useRoute
import { useUserStore } from '../stores/modules/user'
import { login, sendSmsCode as sendSmsCodeApi, passwordLogin } from '../api/user'  // 修改导入名称
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import { debounce } from 'lodash'

const router = useRouter()
const route = useRoute()  // 添加这行
const userStore = useUserStore()

// 登录类型
const loginType = ref('phone')

// 登录表单数据
const loginForm = reactive({
  phone: '',
  smsCode: '',
  username: '',
  password: '',
  verificationCode: '',//图形验证码
  remember: false
})

// 验证码相关
const captchaCanvas = ref(null)
const captchaText = ref('')
const countdown = ref(0)

// 检查并恢复倒计时状态
onMounted(() => {
  // 生成验证码
  refreshCaptcha()
  
  const savedCountdown = localStorage.getItem('smsCountdown')
  const savedTimestamp = localStorage.getItem('smsTimestamp')
  
  if (savedCountdown && savedTimestamp) {
    const remainingTime = Math.ceil(
      (parseInt(savedTimestamp) + parseInt(savedCountdown) * 1000 - Date.now()) / 1000
    )
    
    if (remainingTime > 0) {
      countdown.value = remainingTime
      startCountdown()
    } else {
      // 清除过期的倒计时
      localStorage.removeItem('smsCountdown')
      localStorage.removeItem('smsTimestamp')
    }
  }
})

// 倒计时逻辑封装
const startCountdown = () => {
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      localStorage.removeItem('smsCountdown')
      localStorage.removeItem('smsTimestamp')
    }
  }, 1000)
}

// 生成随机验证码
const generateCaptcha = () => {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = ''
  for (let i = 0; i < 4; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

// 绘制验证码
const drawCaptcha = () => {
  if (!captchaCanvas.value) return
  
  const ctx = captchaCanvas.value.getContext('2d')
  const width = captchaCanvas.value.width
  const height = captchaCanvas.value.height
  
  // 生成新的验证码
  captchaText.value = generateCaptcha()
  
  // 清空画布
  ctx.clearRect(0, 0, width, height)
  
  // 设置背景
  ctx.fillStyle = '#f5f7fa'
  ctx.fillRect(0, 0, width, height)
  
  // 绘制文字
  ctx.font = 'bold 24px Arial'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  
  // 为每个字符设置随机颜色和位置
  for (let i = 0; i < captchaText.value.length; i++) {
    ctx.fillStyle = `rgb(${Math.floor(Math.random() * 150)}, ${Math.floor(Math.random() * 150)}, ${Math.floor(Math.random() * 150)})`
    ctx.save()
    ctx.translate(30 * i + 20, 20)
    ctx.rotate((Math.random() - 0.5) * 0.3)
    ctx.fillText(captchaText.value[i], 0, 0)
    ctx.restore()
  }
  
  // 添加干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.5)`
    ctx.beginPath()
    ctx.moveTo(Math.random() * width, Math.random() * height)
    ctx.lineTo(Math.random() * width, Math.random() * height)
    ctx.stroke()
  }
  
  // 添加干扰点
  for (let i = 0; i < 50; i++) {
    ctx.fillStyle = `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.5)`
    ctx.beginPath()
    ctx.arc(Math.random() * width, Math.random() * height, 1, 0, 2 * Math.PI)
    ctx.fill()
  }
}

// 刷新图形验证码
const refreshCaptcha = () => {
  drawCaptcha()
  loginForm.verificationCode = '' // 清空验证码输入
}

// 发送短信验证码
const loading = ref(false)

const handleSendSmsCode = async () => {
  if (loading.value) return
  
  loading.value = true
  try {
    // 手机号验证
    if (!/^1[3-9]\d{9}$/.test(loginForm.phone)) {
      ElMessage.error('请输入正确的手机号')
      return
    }
    await sendSmsCodeApi(loginForm.phone)//发送验证码
    countdown.value = 60
    localStorage.setItem('smsCountdown', '60')
    localStorage.setItem('smsTimestamp', Date.now().toString())
    
    startCountdown()
    ElMessage.success('验证码已发送')
  } catch (error) {
    console.error('发送验证码失败：', error)
    ElMessage.error(error.message || '发送验证码失败，请重试')
    // 重置倒计时状态
    countdown.value = 0
    localStorage.removeItem('smsCountdown')
    localStorage.removeItem('smsTimestamp')
  } finally {
    loading.value = false
  }
}

// 切换登录方式
const toggleLoginType = () => {
  loginType.value = loginType.value === 'phone' ? 'password' : 'phone'
  // 切换时清空表单
  loginForm.phone = ''
  loginForm.smsCode = ''
  loginForm.username = ''
  loginForm.password = ''
  loginForm.verificationCode = ''
  
  // 如果切换到密码登录，刷新验证码
  if (loginType.value === 'password') {
    setTimeout(() => {
      refreshCaptcha()
    }, 0)
  }
}

// 手机号脱敏处理函数
const maskPhone = (phone) => {
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}

// 验证图形验证码
const validateCaptcha = () => {
  if (!loginForm.verificationCode) {
    ElMessage.error('请输入验证码')
    return false
  }
  
  if (loginForm.verificationCode.toLowerCase() !== captchaText.value.toLowerCase()) {
    ElMessage.error('验证码不正确')
    refreshCaptcha()
    return false
  }
  
  return true
}

// 登录处理
const handleLogin = async () => {
  try {
    if (loginType.value === 'phone') {
      // 手机号登录验证
      if (!loginForm.phone || !loginForm.smsCode) {
        ElMessage.error('请填写完整登录信息')
        return
      }
      
      // 调用手机号登录API
      const res = await login({
        phone: loginForm.phone,
        code: loginForm.smsCode
      })
      
      // 设置用户信息
      const userDTO = res
      userStore.setUserInfo(userDTO)
      
      // 设置访问令牌和过期时间
      userStore.setAccessToken(userDTO.accessToken, userDTO.expires_in)
      
      // 如果用户选择了记住登录状态，设置cookie有效期为7天，否则为会话cookie
      const expires = loginForm.remember ? 7 : null
      const cookieOptions = `path=/; ${expires ? `max-age=${expires * 24 * 60 * 60}` : ''}`
      
      // 设置用户信息到cookie
      document.cookie = `id=${userDTO.id}; ${cookieOptions}`
      document.cookie = `phone=${loginForm.phone}; ${cookieOptions}`
      document.cookie = `displayPhone=${maskPhone(loginForm.phone)}; ${cookieOptions}`
      document.cookie = `nickName=${userDTO.nickName}; ${cookieOptions}`
      document.cookie = `icon=${userDTO.icon || ''}; ${cookieOptions}`
      document.cookie = `email=${userDTO.email || ''}; ${cookieOptions}`
      
      // 登录成功后立即检查商家身份
      try {
        const { isShop } = await import('@/api/shop')
        const isMerchant = await isShop()
        console.log('登录后检查商家身份:', isMerchant)
        if (userDTO && typeof isMerchant === 'boolean') {
          userDTO.isMerchant = isMerchant
          userStore.updateUserMerchantStatus(isMerchant)
        }
      } catch (error) {
        console.error('检查商家身份失败:', error)
      }
      
      ElMessage.success('登录成功')
      // 获取重定向地址
      const redirect = route.query.redirect || '/'
      router.push(redirect)
      
    } else {
      // 账号密码登录验证
      if (!loginForm.username || !loginForm.password) {
        ElMessage.error('请填写完整登录信息')
        return
      }
      
      // 验证图形验证码
      if (!validateCaptcha()) {
        return
      }
      
      // 调用账号密码登录API
      const res = await passwordLogin({
        phone: loginForm.username,
        password: loginForm.password,
        captcha: loginForm.verificationCode,
        type: 'password'
      })
      
      // 设置用户信息
      const userDTO = res
      userStore.setUserInfo(userDTO)
      
      // 设置访问令牌和过期时间
      userStore.setAccessToken(userDTO.accessToken, userDTO.expires_in)
      
      // 如果用户选择了记住登录状态，设置cookie有效期为7天，否则为会话cookie
      const expires = loginForm.remember ? 7 : null
      const cookieOptions = `path=/; ${expires ? `max-age=${expires * 24 * 60 * 60}` : ''}`
      
      // 设置用户信息到cookie
      document.cookie = `id=${userDTO.id}; ${cookieOptions}`
      document.cookie = `nickName=${userDTO.nickName}; ${cookieOptions}`
      document.cookie = `icon=${userDTO.icon || ''}; ${cookieOptions}`
      
      // 登录成功后立即检查商家身份
      try {
        const { isShop } = await import('@/api/shop')
        const isMerchant = await isShop()
        console.log('登录后检查商家身份:', isMerchant)
        if (userDTO && typeof isMerchant === 'boolean') {
          userDTO.isMerchant = isMerchant
          userStore.updateUserMerchantStatus(isMerchant)
        }
      } catch (error) {
        console.error('检查商家身份失败:', error)
      }
      
      ElMessage.success('登录成功')
      // 获取重定向地址
      const redirect = route.query.redirect || '/'
      router.push(redirect)
    }
  } catch (error) {
    console.error('登录失败：', error)
    ElMessage.error('登录失败，请重试')
    if (loginType.value === 'password') {
      refreshCaptcha()
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: var(--bg-color-page);
}

.login-box {
  width: 400px;
  padding: 30px;
  background: var(--bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: var(--text-primary);
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: var(--text-regular);
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 14px;
}

.form-group input:focus {
  border-color: var(--primary-color);
  outline: none;
}

.remember-me {
  margin-bottom: 20px;
  color: var(--text-regular);
}

.login-btn {
  width: 100%;
  padding: 12px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: opacity 0.3s;
}

.login-btn:hover {
  opacity: 0.9;
}

.other-actions {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.other-actions a {
  color: var(--primary-color);
  text-decoration: none;
  font-size: 14px;
}

.third-party-login {
  margin-top: 30px;
  text-align: center;
}

.third-party-login p {
  color: var(--text-secondary);
  margin-bottom: 15px;
}

.login-methods {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.method-item {
  color: var(--text-regular);
  cursor: pointer;
  padding: 5px 15px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  transition: all 0.3s;
}

.method-item:hover {
  color: var(--primary-color);
  border-color: var(--primary-color);
}

.verification-code {
  display: flex;
  gap: 10px;
}

.verification-code input {
  flex: 1;
}

.captcha-image {
  cursor: pointer;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  overflow: hidden;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.captcha-image canvas {
  display: block;
}

.send-code-btn {
  min-width: 120px;
  height: 40px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  padding: 0 15px;  /* 添加内边距 */
  white-space: nowrap;  /* 防止文字换行 */
  display: inline-flex;  /* 使用flex布局 */
  align-items: center;  /* 垂直居中 */
  justify-content: center;  /* 水平居中 */
}

.send-code-btn:disabled {
  background-color: #909399;  /* 使用具体的颜色值替代变量 */
  cursor: not-allowed;
  opacity: 0.7;
  color: white;
}

.login-type-switch {
  text-align: center;
  margin-top: 15px;
  color: var(--primary-color);
  cursor: pointer;
  font-size: 14px;
}

.login-type-switch:hover {
  opacity: 0.8;
}
</style>

// 使用防抖包装发送验证码函数
const debouncedSendSmsCode = debounce(handleSendSmsCode, 300)